package com.eportal.service.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.eportal.aop.LogAnnotation;
import com.eportal.base.BaseDAO;
import com.eportal.domain.Sysopt;
import com.eportal.domain.Sysroles;
import com.eportal.domain.SysrolesTemplate;
import com.eportal.domain.TAgent;
import com.eportal.domain.TCommunity;
import com.eportal.service.SysRolesService;
import com.eportal.service.SysRolesTemplateService;
import com.eportal.util.ValidateUtil;

/**
 * 角色管理业务逻辑接口实现
 */
@Service("sysRolesTemplateService")
public class SysRolesTemplateServiceImpl implements SysRolesTemplateService {
	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(SysRolesTemplateServiceImpl.class.getName());
	
	@Resource(name="dao")
	private BaseDAO dao;
	@Resource(name="sysRolesService")
    private SysRolesService sysRolesService;
	
    @Override
    public List<SysrolesTemplate> list() {
    	return dao.query(" from SysrolesTemplate ");
    }

    @Override
    public SysrolesTemplate get(Long sid) {
        return (SysrolesTemplate) dao.getById(SysrolesTemplate.class, sid);
    }

    @Override
    public void update(SysrolesTemplate role) throws Exception {
        
    	dao.update(role);
    }

	@Override
	public SysrolesTemplate getByTmpType(String tmpType) {
		StringBuffer sb = new StringBuffer("from SysrolesTemplate where tmpType='");
		sb.append(tmpType);
		sb.append("'");
		return (SysrolesTemplate) dao.loadObject(sb.toString());
	}

	 /**
     * 角色模板修改保存
     */
	@Override
    @LogAnnotation(operateDescribe="角色模板修改")  
    public Map<String, Object> updateMethod(SysrolesTemplate sysrolesTemplate) {
        String msg = ValidateUtil.validate(sysrolesTemplate);
        result.put("objectId", sysrolesTemplate.getSid());
        if (msg == null || msg.trim().length() == 0) {
            try {
            	SysrolesTemplate entity = get(sysrolesTemplate.getSid());
            	String mListBefore = entity.getmList();
            	Sysopt  user= (Sysopt)getSession().getAttribute("user");
            	entity.setRtName(sysrolesTemplate.getRtName());
            	entity.setmList(sysrolesTemplate.getmList());
            	entity.setuUserName(Long.toString(user.getSid()));
            	entity.setuTime(new Timestamp(System.currentTimeMillis()));
            	update(entity);
            	if(!mListBefore.equals(entity.getmList())){
	            	//模板修改后，应用到所有的超管角色
	            	sysRolesService.updateAllManagerRole(entity,mListBefore);
            	}
                result.put("code", 1);
                result.put("msg", "操作成功");
            } catch (Exception e) {
                log.error("角色更新失败", e);
                result.put("code", 0);
                result.put("msg", "操作失败");
            }
        } else {
            result.put("code", 0);
            result.put("msg", msg);
        }
        return result;
    }
	
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }

	 /**
	   * 创建合作方超级管理员
	   */
	@Override
	public Map<String, Object> creatManager(TAgent tagent) {
	    Map<String, Object> result = new HashMap<String, Object>();
	    try {	
	  		Sysopt  user= (Sysopt)getSession().getAttribute("user");
	  	 	//查找模板
	  		SysrolesTemplate sysrolesTemplate;
	  		if("0".equals(tagent.getType())){
	  			sysrolesTemplate = getByTmpType("1");
	  		}else{
	  			sysrolesTemplate = getByTmpType("3");
	  		}
	      	//创建合作方超级管理员合作方
	      	Sysroles role  = new Sysroles();
	      	role.setrName(tagent.getAgtName()+"公司超管角色");
	      	role.setrAgtent(tagent.getSid()+"");
	      	role.setrCommunity("0");
	      	if("0".equals(tagent.getType())){
	      		role.setrLevel(1);
	      	}else{
	      		role.setrLevel(3);
	      	}
	      	role.setStatus("1");
	      	role.setmList(role.getmList());
	  		role.setIsAdmin("1");
	  		role.setUserName(Long.toString(user.getSid()));
	  		role.setOptTime(new Timestamp(System.currentTimeMillis()));
	      	role.setmList(sysrolesTemplate.getmList());
	      	Sysroles roleManager = sysRolesService.add(role);
	      	result.put("roleId", roleManager.getSid());
	      	result.put("code", 1);
		    result.put("msg", "建公司超级管理员角色成功");
	    } catch (Exception e) {	
          log.error("创建公司超级管理员角色失败", e);
          result.put("code", 0);
          result.put("msg", "创建公司超级管理员角色失败，agtcode:"+tagent.getAgtCode());
	  	}
      return result;
  }

	@Override
	public Map<String, Object> creatComuManager(TCommunity tCommunity) {
		 Map<String, Object> result = new HashMap<String, Object>();
		 try {	
			 Sysopt  user= (Sysopt)getSession().getAttribute("user");
	    	//查找模板
	        SysrolesTemplate sysrolesTemplate = getByTmpType("2");
	        //创建社区超级管理员社区
	        Sysroles role  = new Sysroles();
	        role.setrName(tCommunity.getCommunityName()+"社区超管角色");
	        role.setrAgtent(tCommunity.getAgtCode());
	        role.setrCommunity(tCommunity.getSid()+"");
	        role.setrLevel(2);
	        role.setStatus("1");
	        role.setmList(role.getmList());
	    	role.setIsAdmin("1");
	    	role.setUserName(Long.toString(user.getSid()));
	    	role.setOptTime(new Timestamp(System.currentTimeMillis()));
	        role.setmList(sysrolesTemplate.getmList());
	        Sysroles roleManager = sysRolesService.add(role);
	        result.put("roleId", roleManager.getSid());
	      	result.put("code", 1);
		    result.put("msg", "创建社区超级管理员角色成功");
	    } catch (Exception e) {	
	      log.error("创建社区超级管理员角色失败", e);
	      result.put("code", 0);
	      result.put("msg", "创建社区超级管理员角色失败，tCommunity sid:"+tCommunity.getSid());
	  	}
		return result;
	}
}
